<template>
  <div class="publish-container">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
            <el-breadcrumb separator-class="el-icon-arrow-right">
                <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item>{{$route.query.id ? '修改文章' : '发布文章'}}</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <el-form ref="publish-form" :model="article" label-width="80px" :rules="formRules" >
            <el-form-item label="标题" prop="title">
                <el-input v-model="article.title" placeholder="请输入标题"></el-input>
            </el-form-item>
            <el-form-item label="内容" prop="content">
                <!-- <el-input type="textarea" v-model="article.content"></el-input> -->
                <el-tiptap :extensions="extensions" height="350" placeholder="请输入文章内容" v-model="article.content"></el-tiptap>
            </el-form-item>
             <el-form-item label="封面">
                <el-radio-group v-model="article.cover.type">
                <el-radio :label="1">单图</el-radio>
                <el-radio :label="3">三图</el-radio>
                <el-radio :label="0">无图</el-radio>
                <el-radio :label="-1">自动</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="频道" prop="channel_id">
                <el-select v-model="article.channel_id" placeholder="请选择频道">
                    <el-option :label="item.name" :value="item.id" v-for="item in channels" :key="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onPublish(false)">立即发布</el-button>
                <el-button  @click="onPublish(true)">存入草稿</el-button>
            </el-form-item>
        </el-form>
      </el-card>
  </div>
</template>

<script>
import 'element-tiptap/lib/index.css';
import { getArticleChannel,addArticle,updateArticle,getByIdArticle } from '@/api/article'
import { uploadImage } from '@/api/image'
import {
  ElementTiptap,
  Doc,
  Text,
  Paragraph,
  Heading,
  Bold,
  Underline,
  Italic,
  Strike,
  ListItem,
  BulletList,
  OrderedList,
  TodoItem,
  TodoList,
  TextAlign,
  Indent,
  LineHeight,
  HorizontalRule,
  Image,
  CodeBlock,
  Blockquote,
  HardBreak,
  TrailingNode,
  History,
  Table,
  TableHeader,
  TableCell,
  TableRow,
  FormatClear,
  TextColor,
  TextHighlight,
  Preview,
  Print,
  Fullscreen,
  SelectAll,
  FontType,
  FontSize,
  CodeView
} from 'element-tiptap'
export default {
  name:'PublishIndex',
  components:{
      'el-tiptap': ElementTiptap,
  },
  data () {
    return {
        article:{
            title:'',
            content:'',
            cover:{
                type:0,
                images:[] 
            },
            channel_id: null
        },
        channels:[],
        extensions: [
            new Doc(),
            new Text(),
            new Paragraph(),
            new Heading({ level: 5 }),
            new Bold({ bubble: true }), // render command-button in bubble menu.
            new Underline({ bubble: true, menubar: false }), // render command-button in bubble menu but not in menubar.
            new Italic(),
            new Strike(),
            new ListItem(),
            new BulletList(),
            new OrderedList(),
            new TodoItem(),
            new TodoList(),
            new TextAlign(),
            new Indent(),
            new LineHeight(),
            new HorizontalRule(),
            new Image({
                uploadRequest(file){
                    const fd = new FormData();
                    fd.append('image',file);
                     return uploadImage(fd).then(res => {
                        return res.data.data.url;
                    })
                }
            }),
            new CodeBlock(),
            new Blockquote(),
            new Table(),
            new TableHeader(),
            new TableCell(),
            new TableRow(),
            new FormatClear(),
            new TextColor(),
            new TextHighlight(),
            new Preview(),
            new Print(),
            new Fullscreen(),
            new SelectAll(),
            new FontType(),
            new FontSize(),
            new CodeView(),
            new HardBreak(),
            new TrailingNode(),
            new History(),
        ],
        formRules:{
            title: [
                {required: true, message: '请输入文章标题', trigger:'blur'},
                {min: 5, max:30, message: '长度为5-30个字符', trigger:'blur'},
            ],
            content: [
                {required: true, message:'请输入文章内容', trigger:'change'},
                {
                    validator(rule, value, callback){
                        if (value === '<p></p>') {
                            callback(new Error('请输入文章内容'));
                        }else{
                            callback();
                        }
                    }
                }
            ],
            channel_id:[
                {required: true, message: '请选择频道'}
            ]
        }
    }
  },
  methods: {
      loadChannels(){
          getArticleChannel().then(res => {
              this.channels = res.data.data.channels;
          })
      },
      onPublish(draft = false) {
          this.$refs['publish-form'].validate(valid => {
            if(!valid){
                return ;
            }
            console.log(valid)
            const articleId = this.$route.query.id;
            if(articleId){
                updateArticle(articleId,this.article,draft).then(res => {
                    this.$message({
                        message: `${draft ? '存入草稿' : '修改'}成功`,
                        type: 'success'
                    })
                    this.$router.push('/article');
                })
            }else{
                addArticle(this.article,draft).then(res => {
                    this.$message({
                        message: `${draft ? '存入草稿' : '发布'}成功`,
                        type: 'success'
                    })
                    this.article = '';
                    this.$router.push('/article');
                })
            }
          })
          
      },
      loadArticle(){
          getByIdArticle(this.$route.query.id).then(res => {
              this.article = res.data.data;
          })
      }
  },
  created () {
      this.loadChannels();
      if (this.$route.query.id){
          this.loadArticle();
      }
  }
}
</script>